import math
import time

import event.event
import logo.Mlog
from event.event import take_screenshot, click_icons_pot
from match.photo import find_icons_semblance_screenshot
from taskPro import taskPro


def chooseCharacter(index: int) -> bool:
    index = index - 1
    if index < 0:
        logo.Mlog.logger.error("用户传入的下标为负数")
        return False
    # 进入选择角色界面
    ast = taskPro.getAction("cutPlayer")
    ast.click()
    # 等3秒
    time.sleep(7)
    p1, st = getpot(['./tasks/icos/chooseRole/bj01.png'])
    p2, st = getpot(['./tasks/icos/chooseRole/bj02.png'])
    if len(p1) == 0 or len(p2) == 0:
        return False
    setpot(p1, p2, index)
    return True


def chooseCharacter3(index: int) -> bool:
    index = index - 1
    if index < 0:
        logo.Mlog.logger.error("用户传入的下标为负数")
        return False
    # 进入选择角色界面
    # 等3秒
    time.sleep(7)
    p1, st = getpot(['./tasks/icos/chooseRole/bj01.png'])
    p2, st = getpot(['./tasks/icos/chooseRole/bj02.png'])
    if len(p1) == 0 or len(p2) == 0:
        return False
    setpot(p1, p2, index)
    return True
#
#
# def chooseCharacter2(index: int) -> bool:
#     if index < 0:
#         logo.Mlog.logger.error("用户传入的下标为负数")
#         return False
#     # 进入选择角色界面
#     ast = taskPro.getAction("cutPlayer2")
#     ast.click()
#     # 等3秒
#     time.sleep(1)
#     p1, st = getpot(['./tasks/icos/chooseRole/cch.png'])
#     if len(p1) == 0:
#         return False
#     xzjs(p1, index)
#     return True


def getpot(path: [str]):
    icon_paths = path
    # 截取屏幕截图
    screenshot = take_screenshot()
    # 查找ICO图标在截图中的位置
    matches, annotated_screenshot = find_icons_semblance_screenshot(screenshot, icon_paths)
    return matches, screenshot


def setpot(pot1, pot2, i: int = 1):
    offset = int((pot2[0].center_x - pot1[0].center_x) * 2 / 5)
    y = int(pot2[0].center_y - (pot2[0].center_y - pot1[0].center_y) / 2)
    x = int(pot1[0].center_x + offset / 2)
    logo.Mlog.logger.debug(f"向上滑动 index={i}")
    if i > 4:
        dis = i // 4
        pot = i % 4-1
        x = x + pot * offset
        logo.Mlog.logger.debug(f"向上滑动pot={pot}")
        dis = dis * 2
        for _ in range(dis):
            event.event.move_mouse(x, y, (pot2[0].center_y-pot1[0].center_y)/3, "up")
            logo.Mlog.logger.debug("向上滑动00")
            time.sleep(2)
        click_icons_pot(x, y)
        time.sleep(0.3)
        click_icons_pot(pot2[0].center_x, pot2[0].center_y)
        return
        # time.sleep(5)

    # print(f"offset={offset},y={y}")
    click_icons_pot(x+ offset * i, y)
    time.sleep(1)
    click_icons_pot(pot2[0].center_x, pot2[0].center_y)


def xzjs(pot, i: int = 1):
    x = pot[0].center_x
    y = pot[0].center_y + pot[0].top_left[1] / 2
    # print(x, y)
    offset = pot[0].top_left[1] * 102 / 88
    # print(pot[0].top_left[1], offset)
    click_icons_pot(int(x), int(y + offset * i - offset / 2))
